package com.bear.userInfo.jdbc.imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.bear.PlatFormDao.userInfo.MessageDao;
import com.bear.model.entity.balance.MoneyList;
import com.bear.model.entity.balance.MoneyType;
import com.bear.model.entity.userInfo.Message;

@Repository
public class MessageDaoImp implements MessageDao{

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public List<Message> getAllMessages(int userid) {
		String sqlStr = "select id, messagetype,content,fromuser,touser,time,isdone,topicid" +
				" from message where isdone=0 and touser=?";
		final List<Message> messagelist = new ArrayList<Message>();
		jdbcTemplate.query(sqlStr,new Object[]{userid},
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
							Message message = new Message();
							message.setId(rs.getInt("id"));
							message.setMessageType(rs.getInt("messagetype"));
							message.setContent(rs.getString("content"));
							message.setFrom(rs.getInt("fromuser"));
							message.setTo(rs.getInt("touser"));
							message.setTime(rs.getTimestamp("time"));
							message.setIsdone(rs.getInt("isdone"));
							message.setTopicid(rs.getInt("topicid"));
							messagelist.add(message);
					}
				});
		return messagelist;
	}

	@Override
	public void addMessage(Message message) {
		String sqlStr = "insert into message(messagetype,content,fromuser,touser,time,isdone,topicid)" +
				" values(?,?,?,?,?,?,?)";
		Object[] args= {message.getMessageType(),message.getContent(),message.getFrom(),message.getTo(),message.getTime(),message.getIsdone(),message.getTopicid()};
		jdbcTemplate.update(sqlStr,args);
		
	}

	@Override
	public Integer getCount(int userid) {
		String sql = "select count(*) from message where isdone=0 and touser="+userid;
		return jdbcTemplate.queryForInt(sql);
	}

	@Override
	public void setisdone(int messageid) {
		String sql = "update message set isdone=1 where id="+messageid;
		jdbcTemplate.execute(sql);
		
	}

}
